package com.pipe.connector;

import com.pipe.connector.nettyhandler.BasePackageDecoder;
import com.pipe.connector.nettyhandler.ExceptionHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Kiven
 */
public class NettyClient{
	private Logger log = LoggerFactory.getLogger(NettyClient.class);

	private EventLoopGroup workerGroup;
	private ChannelInboundHandler handler;

	NettyClient(ChannelInboundHandler handler) {
		this.handler = handler;
	}

	void connect(String ip, int port){
		Bootstrap bootstrap = new Bootstrap();
		workerGroup = new NioEventLoopGroup();
		bootstrap.group(workerGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(handler)
						.addLast(new ExceptionHandler());
			}
		});
		try {
			bootstrap.connect(ip, port);
		} catch (Exception e) {
			log.error("[CONNECT] - Remote connect error!", e);
		}
	}

	void close(){
		workerGroup.shutdownGracefully();
	}
}